#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2017-08-16 10:39:38
# Project: omqq

from pyspider.libs.base_handler import *
from selenium import webdriver
import config as cf
import pymysql
import time
import error_handler
try:
    from urllib.parse import urlencode
except Exception :



    from urllib import urlencode
import json
from db_action import store_info_qq

## plat_id 7 企鹅号

class Handler(BaseHandler):
    crawl_config = {
    }

    def __init__(self):
        self.b = webdriver.PhantomJS()
        conn = pymysql.connect(**cf.mysql_option)
        cursor = conn.cursor()
        self.c = conn
        self.cursor = cursor

    @every(minutes=4 * 60)
    def on_start(self):
        self.cursor.execute("select * from qp.med_plat_account WHERE plat_id = 7;")
        accounts = self.cursor.fetchall()
        for i in accounts:
            try:
                if self.login_qq(i):
                    self.get_info_for_qq(i)
                else:
                    # 这里做报错处理
                    err = "企鹅登陆失败"
                    print(err)
                    error_handler.handler_error(err)
            except Exception as e:
                print(e)
                pass
        return {"task":"qq",
                "message":"成功"}

    def login_qq(self,user_info):
        self.b.get("https://m.om.qq.com/mobile/login")
        time.sleep(2)
        input = self.b.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/label[1]/input')
        pw = self.b.find_element_by_xpath('//*[@id="app"]/div/div/div/div/form/label[2]/input')
        input.send_keys(user_info.get("account_login_name"))
        pw.send_keys(user_info.get("account_login_password"))
        bt = self.b.find_element_by_xpath('//*[@id="app"]/div/div/div/div/div/button')
        bt.click()
        time.sleep(2)
        try:
            self.b.find_element_by_class_name("om-index")
        except Exception as e:
            print(e)
            return False
        return True

    def get_info_for_qq(self,user_info,cursor=''):

        data = {
            "commentflag":0,
            "category":"all",
            #"cursor":cursor,
            "limit":10,
            "_r":int(time.time() * 1000)
        }
        self.b.get("https://m.om.qq.com/article/list?" + urlencode(data) + '&cursor=' + cursor.replace(" ", "+"))

        video_info = json.loads(self.b.find_element_by_tag_name("body").text)['data']
        for i in video_info['articles']:
            store_info_qq(i,user_info)
        if video_info['cursor']['hasnext']:
            return self.get_info_for_qq(user_info,video_info['cursor']['next'].replace(" ","+"))
        return



